//
//  DetailListViewController.m
//  翼安保
//
//  Created by duzhi on 2024/4/23.
//

#import "DetailListViewController.h"
#import "DetailListModel.h"
#import "DetailListCell0.h"
#import "DetailListCell1.h"
#import "DetailListCellHeader.h"
#import "DetailApi.h"

@interface DetailListViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) DetailListJumpHelp   *jumpHelp;
@end

@implementation DetailListViewController

- (void)setDatas:(NSMutableArray *)datas {
    _datas = datas;
    DetailListModel *firstModel = _datas.firstObject;
    firstModel.isOpen = YES;
    [self.tableView reloadData];
}

- (void)setType:(int)type {
    _type = type;
    if (_type == 0) {
        self.navigationItem.title = @"用品详情";
    }
    if (_type == 1) {
        self.navigationItem.title = @"我的领用";
    }
    if (_type == 2) {
        self.navigationItem.title = @"用品领用";
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NewsBigButton *backButton = [NewsBigButton new];
    [backButton setBackgroundImage:[UIImage imageNamed:@"back_black_26x26"] forState:0];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled=YES;
    self.navigationController.interactivePopGestureRecognizer.delegate=self;
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:NO];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    DetailListModel *model = self.datas[section];
    if (!model.isOpen) {
        return 1;
    }
//    if (model.bindStatus == 1) {
//        return 15;
//    }
//    return 10;
    
    //客户要求显示所有信息
    return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailListModel *model = self.datas[indexPath.section];
    if (indexPath.row == 0) {
        DetailListCellHeader * cell0 = (DetailListCellHeader *)[tableView dequeueReusableCellWithIdentifier:@"DetailListCellHeader" forIndexPath:indexPath];
        model.index = (int)indexPath.section;
        cell0.model = model;
        Weak(wself, self)
        cell0.openBlock = ^(int index) {
            [wself.tableView reloadData];
        };
        return cell0;
    }
    if(indexPath.row == 1||indexPath.row == 10){
        DetailListCell1 * cell0 = (DetailListCell1 *)[tableView dequeueReusableCellWithIdentifier:@"DetailListCell1" forIndexPath:indexPath];
        [cell0 setDesc:indexPath.row == 1?@"用品信息:":@"领用人信息:"];
       cell0.hidden = [self cellNeedHidden:indexPath];
        return cell0;
    }
    DetailListCell0 *cell = (DetailListCell0 *)[tableView dequeueReusableCellWithIdentifier:@"DetailListCell0" forIndexPath:indexPath];
    switch (indexPath.row) {
        case 2:
            [cell setTitle:@"制造日期" desc:model.produceTime];
            break;
        case 3:
            [cell setTitle:@"入库日期" desc:model.inStockTime];
            break;
        case 4:
            [cell setTitle:@"订购日期" desc:model.orderTime];
            break;
        case 5:
            [cell setTitle:@"出库日期" desc:model.outStockTime];
            break;
        case 6:
            [cell setTitle:@"到货日期" desc:model.arriveDate];
            break;
        case 7:
            [cell setTitle:@"保质时长" desc:model.period];
            break;
        case 8:
            [cell setTitle:@"到期日期" desc:model.expDate];
            break;
        case 9:
            [cell setTitle:@"预警状态" desc:model.timeState];
            break;
        case 11:
            [cell setTitle:@"领用人姓名" desc:model.staffName];
            break;
        case 12:
            [cell setTitle:@"电话" desc:model.phone];
            break;
        case 13:
            [cell setTitle:@"身份证号" desc:model.idCard];
            break;
        case 14:
            [cell setTitle:@"所属公司" desc:model.staffCompany];
            break;
        default:
            break;
    }
    cell.hidden = [self cellNeedHidden:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return relativeWidth(60);
    }
    if ([self cellNeedHidden:indexPath]) {
       return 0;
    }
    return relativeWidth(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    //type：0-用品详情 1-我的领用 2-用品领用 3-替换
    if (self.type == 0) {
        return nil;
    }
    DetailListModel *model = self.datas[section];
    UIView *view = [UIView new];
    if (self.type == 1) {
        //已报废/已更换/超期/临期/正常
        if([model.timeState isEqual:@"已报废"]||[model.timeState isEqual:@"已更换"]) {
            UILabel *label = [UILabel new];
            label.text = model.timeState;
            label.font = [UIFont systemFontOfSize:relativeWidth(13)];
            label.textColor = [UIColor redColor];
            [view addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(relativeWidth(20));
                make.centerY.mas_equalTo(0);
            }];
        }else {
            UIColor *textColor = [model.timeState isEqual:@"超期"]||[model.timeState isEqual:@"临期"]?[UIColor redColor]:UIColorFromRGB(0x1296db);
            CGFloat fontSize   = relativeWidth(13);
            
            UIView *rightView = nil;
            if ([model.timeState isEqual:@"超期"]||[model.timeState isEqual:@"临期"]) {
                NewsBigButton *scrapBindButton = [NewsBigButton new];
                scrapBindButton.tag = section+10000;
                [scrapBindButton setTitle:@"报废" forState:0];
                scrapBindButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
                [scrapBindButton setTitleColor:textColor forState:0];
                [scrapBindButton addTarget:self action:@selector(scrapBind:) forControlEvents:UIControlEventTouchUpInside];
                [view addSubview:scrapBindButton];
                [scrapBindButton mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(relativeWidth(20));
                    make.centerY.mas_equalTo(0);
                }];
                
                NewsBigButton *changeBindButton = [NewsBigButton new];
                changeBindButton.tag = section+10000;
                changeBindButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
                [changeBindButton setTitle:@"更换" forState:0];
                [changeBindButton setTitleColor:textColor forState:0];
                [changeBindButton addTarget:self action:@selector(clickChangeBind:) forControlEvents:UIControlEventTouchUpInside];
                [view addSubview:changeBindButton];
                [changeBindButton mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(scrapBindButton.mas_right).offset(relativeWidth(20));
                    make.centerY.mas_equalTo(0);
                }];
                
                rightView = changeBindButton;
            }
         
            NewsBigButton *canceBindButton = [NewsBigButton new];
            canceBindButton.tag = section+10000;
            canceBindButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
            [canceBindButton setTitle:@"取消领用" forState:0];
            [canceBindButton setTitleColor:textColor forState:0];
            [canceBindButton addTarget:self action:@selector(clickCanceBind:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:canceBindButton];
            [canceBindButton mas_makeConstraints:^(MASConstraintMaker *make) {
                if (rightView) {
                    make.left.mas_equalTo(rightView.mas_right).offset(relativeWidth(20));
                }else {
                    make.left.mas_equalTo(relativeWidth(20));
                }
                make.centerY.mas_equalTo(0);
            }];
        }
            
    }
    if (self.type == 2) {
        NewsBigButton *bindButton = [NewsBigButton new];
        bindButton.tag = section+10000;
        bindButton.titleLabel.font = [UIFont systemFontOfSize:relativeWidth(13)];
        if (model.bindStatus == 1||[model.timeState isEqual:@"已报废"] ) {
            if ([model.timeState isEqual:@"已报废"]) {
                [bindButton setTitle:@"已报废" forState:0];
            }else{
                [bindButton setTitle:@"已领用" forState:0];
            }
            bindButton.userInteractionEnabled = NO;
            [bindButton setTitleColor:[UIColor redColor] forState:0];
        }else {
            [bindButton setTitle:@"领用" forState:0];
            [bindButton setTitleColor:UIColorFromRGB(0x1296db) forState:0];
        }
        [bindButton addTarget:self action:@selector(clickBind:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:bindButton];
        [bindButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(relativeWidth(20));
            make.centerY.mas_equalTo(0);
        }];
    }
    if (self.type == 3) {
        NewsBigButton *bindButton = [NewsBigButton new];
        bindButton.tag = section+10000;
        bindButton.titleLabel.font = [UIFont systemFontOfSize:relativeWidth(13)];
        [bindButton setTitle:@"替换" forState:0];
        [bindButton setTitleColor:UIColorFromRGB(0x1296db) forState:0];
        [bindButton addTarget:self action:@selector(clickDidChangeBind:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:bindButton];
        [bindButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(relativeWidth(20));
            make.centerY.mas_equalTo(0);
        }];
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.type == 0) {
        return 0;
    }
    return relativeWidth(30);
}

- (BOOL)cellNeedHidden:(NSIndexPath *)indexPath {
    //只隐藏身份证，其他不处理
    if (indexPath.row == 13) {
        return YES;
    }
    return NO;

    DetailListModel *model = self.datas[indexPath.section];
    if (!model.isOpen) {
        return YES;
    }
    BOOL atLeastOne = model.staffName.length >0||model.staffCompany.length >0||model.phone.length >0||model.idCard.length >0;
    switch (indexPath.row) {
        case 0:
            return NO;
            break;
        case 1:
            return NO;
            break;
        case 2:
            return !(model.produceTime.length >0);
            break;
        case 3:
            return !(model.inStockTime.length >0);
            break;
        case 4:
            return !(model.orderTime.length >0);
            break;
        case 5:
            return !(model.outStockTime.length >0);
            break;
        case 6:
            return !(model.arriveDate.length >0);
            break;
        case 7:
            return !(model.period.length >0);
            break;
        case 8:
            return !(model.expDate.length >0);
            break;
        case 9:
            return !(model.timeState.length >0);
            break;
        case 10:
            if (model.bindStatus == 0||!atLeastOne) {
                return YES;
            }
            return NO;
            break;
        case 11:
            if (model.bindStatus == 0) {
                return YES;
            }
            return !(model.staffName.length >0);
            break;
        case 12:
            if (model.bindStatus == 0) {
                return YES;
            }
            return !(model.phone.length >0);
            break;
        case 13:
            if (model.bindStatus == 0) {
                return YES;
            }
            return !(model.idCard.length >0);
            break;
        case 14:
            if (model.bindStatus == 0) {
                return YES;
            }
            return !(model.staffCompany.length >0);
            break;
        default:
            break;
    }
    return NO;
}

- (void)clickCanceBind:(UIButton *)button {
    DetailListModel *model = self.datas[button.tag-10000];
    [self alertTitle:[NSString stringWithFormat:@"确定取消绑定%@?",model.identifyId] ok:^{
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"code"] = model.identifyId;
        [[AFNNetWorkManager shareAFNNetWorkManager] Get:canceBindUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
            if (result.code == 200) {
                [self.datas removeObject:model];
                [self.tableView reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
            }else {
                [MBProgressHUD showTextHUD:result.msg];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [MBProgressHUD showTextHUD:@"请检查网络设置"];
        }];
    }];
}

- (void)clickBind:(UIButton *)button {
    DetailListModel *model = self.datas[button.tag-10000];
    [self alertTitle:[NSString stringWithFormat:@"确定绑定%@?",model.identifyId] ok:^{
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"code"] = model.identifyId;
        [[AFNNetWorkManager shareAFNNetWorkManager] Get:bindUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
            if (result.code == 200) {
                model.bindStatus = 1;
                button.userInteractionEnabled = NO;
                self.datas = @[model].mutableCopy;
                [self.tableView reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
            }else {
                [MBProgressHUD showTextHUD:result.msg];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [MBProgressHUD showTextHUD:@"请检查网络设置"];
        }];
    }];
}

- (void)clickChangeBind:(UIButton *)button {
    DetailListModel *model = self.datas[button.tag-10000];
    UIAlertController *alertview = [UIAlertController alertControllerWithTitle:@"请选择以下任一种方式开始查询：" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *input = [UIAlertAction actionWithTitle:@"输码查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.jumpHelp.replacedModel = model;
        [self.jumpHelp inputSearch:self type:3];
    }];
    UIAlertAction *scan = [UIAlertAction actionWithTitle:@"扫码查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.jumpHelp.replacedModel = model;
        [self.jumpHelp scanSearch:self type:3];
    }];
    UIAlertAction *nfc = [UIAlertAction actionWithTitle:@"NFC查询" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.jumpHelp.replacedModel = model;
        [self.jumpHelp NFCSearch:self type:3];
    }];
    UIAlertAction *cance = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertview addAction:input];
    [alertview addAction:scan];
    [alertview addAction:nfc];
    [alertview addAction:cance];
    [self presentViewController:alertview animated:YES completion:nil];
}

- (void)clickDidChangeBind:(UIButton *)button {
    DetailListModel *model = self.datas[button.tag-10000];
    [self alertTitle:[NSString stringWithFormat:@"确定用%@替换%@?",model.identifyId,self.replacedModel.identifyId] ok:^{
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"codeBefore"] = self.replacedModel.identifyId;
        dic[@"codeAfter"] = model.identifyId;
        [[AFNNetWorkManager shareAFNNetWorkManager] Post:replaceUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
            if (result.code == 200) {
                [MBProgressHUD showTextHUD:@"替换成功"];
                [self.navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
                if (self.detailListFinishReplaceBlock) {
                    self.detailListFinishReplaceBlock(self.replacedModel, model);
                }
            }else {
                [MBProgressHUD showTextHUD:result.msg];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [MBProgressHUD showTextHUD:@"请检查网络设置"];
        }];
    }];
}

- (void)scrapBind:(UIButton *)button {
    DetailListModel *model = self.datas[button.tag-10000];
    [self alertTitle:[NSString stringWithFormat:@"确定报废%@?",model.identifyId] ok:^{
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"code"] = model.identifyId;
        [[AFNNetWorkManager shareAFNNetWorkManager] Post:scrapUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
            if (result.code == 200) {
                model.timeState = @"已报废";
                [self.tableView reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
            }else {
                [MBProgressHUD showTextHUD:result.msg];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [MBProgressHUD showTextHUD:@"请检查网络设置"];
        }];
    }];
}

- (void)alertTitle:(NSString *)title ok:(void(^)(void))okBlock {
    UIAlertController *alertview = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *left = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *right = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (okBlock) {
            okBlock();
        }
    }];
    [alertview addAction:left];
    [alertview addAction:right];
    [self presentViewController:alertview animated:YES completion:nil];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1) style:UITableViewStyleInsetGrouped];
        _tableView .delegate = self;
        _tableView .dataSource = self;
        _tableView .estimatedRowHeight = 0;
        _tableView .separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView .showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[DetailListCell0 class] forCellReuseIdentifier:@"DetailListCell0"];
        [_tableView registerClass:[DetailListCell1 class] forCellReuseIdentifier:@"DetailListCell1"];
        [_tableView registerClass:[DetailListCellHeader class] forCellReuseIdentifier:@"DetailListCellHeader"];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.top.mas_equalTo(0);
        }];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, kiPhoneX_Bottom_Height, 0);
    }
    return _tableView;
}

- (DetailListJumpHelp *)jumpHelp {
    if (!_jumpHelp) {
        _jumpHelp = [DetailListJumpHelp new];
    }
    return _jumpHelp;
}
@end
